<template>
	<view class="pBox">
		<view class="playerBox" v-if="musicData && musicData.id" @touchstart="touchstart" @touchend="touchmove">
			<view  @click.stop="toPlayer">
				<image mode="aspectFill" :src="musicData.cover"></image>
				<view>
					<view>{{musicData.singer}} - {{musicData.title}}</view>
					<view>
						<template v-if="isRequest && lyrics.length==0">此歌曲暂时没有歌词</template>
						<template v-else>{{palylrc}}</template>
					</view>
				</view>
			</view>
			<view>
				<view>
					<cicon v-if="!isPlay" name="play" @click="play"></cicon>
					<cicon v-else name="pause" @click="pause"></cicon>
				</view>
				<view @click="showPlaylist">
					<cicon name="playlist"></cicon>
				</view>
			</view>
			
			
			
			 
		</view>
		
		<uni-transition class="bigPlayer" mode-class="slide-bottom" :show="showBigPlayer">	
			<big-player ref="bigplayer"></big-player>
		</uni-transition>
		
		<!-- 播放队列 -->
		<play-list ref="playList"></play-list>
	</view>
</template>

<script>
	import bigPlayer from "@/components/player.vue"
	import playList from "@/components/playList.vue"
	export default {
		name:"miniPlayer",
		components: {
			bigPlayer,
			playList,
		},
		data() {
			return {
				isRequest:false, 
				musicData:[],
				audio: null, //音频对象
				isPlay:false,//当前播放状态
				palylrc:null, //当前播放的歌词
				lyrics:[], //歌词
				lyricTime:0, //歌词对应的时间
				playerTop:100,
				collect:0,
				showBigPlayer:false,
				startX:0,
				startY:0, 
				musicNotification:null,
				isCreateNotification:false, 
				isLockActivity:false
			};
		},
		created() {
			this.musicNotification = uni.requireNativePlugin('XZH-musicNotification');
			this.musicNotification.switchNotification(true);
			this.initNotification()
		},
		mounted() {
			//获取上次播放的记录和歌词
			let playMusic = this.$TOOL.data.get('playMusic')
			this.musicData = playMusic
			//当前歌曲是否已经收藏
			this.isCollect()
			this.lyrics = this.$TOOL.data.get('lyrics')
			this.setInitlycTop()
			
			 
			
		},
		
		unmounted(){
			// 移除监听生命周期事件回调
			plus.globalEvent.removeEventListener('musicLifecycle')
			// 移除暂停或播放按钮事件回调监听
			plus.globalEvent.removeEventListener('musicNotificationPause')
			// 移除播放上一首按钮事件回调监听
			plus.globalEvent.removeEventListener('musicNotificationPrevious')
			// 移除播放下一首按钮事件回调监听
			plus.globalEvent.removeEventListener('musicNotificationNext')
			plus.globalEvent.removeEventListener('musicNotificationFavourite') 
			 
			// 移除耳机事件回调监听
			// plus.globalEvent.removeEventListener('musicMediaButton')
			// 移除通知栏进度条拖动事件回调
			plus.globalEvent.removeEventListener('musicSeekTo')
		},
		
		 
		methods:{
			touchstart(event) {
			    this.startX = event.changedTouches[0].pageX
			    this.startY = event.changedTouches[0].pageY
			},
			
			touchmove(event) {  
			  
				  var moveEndX = event.changedTouches[0].pageX
				  var moveEndY = event.changedTouches[0].pageY
				  var X = moveEndX - this.startX
				  var Y = moveEndY - this.startY
				  if (Math.abs(X) > Math.abs(Y) && X > 50) {
					  //右滑
					  this.nextPlay()
				  } else if (Math.abs(X) > Math.abs(Y) && X < 50) {
					  //左滑
					  this.prevPlay()
				  } else if (Math.abs(Y) > Math.abs(X) && Y > 50) {
					  return false
				  } else if (Math.abs(Y) > Math.abs(X) && Y < 50) {
					  this.toPlayer()
				  } 
			},
			
			
			setInitlycTop(){
				let sysInfo = uni.getSystemInfoSync()
				let screenHeight = sysInfo.screenHeight
				let devicePixelRatio = sysInfo.devicePixelRatio
				// height: calc( 90vh - 480rpx);
				let bHeight = screenHeight*0.9 - (480/devicePixelRatio)
				
				this.$refs.bigplayer.lycTop = bHeight/2 - 20 
				this.$refs.bigplayer.olycTop = bHeight/2 - 20 
			},
			
			
			playMusic(music){
				this.lyricTime = 0
				this.$refs.bigplayer.currentLycIndex = 0
				this.isRequest = false
				this.palylrc = null
				this.lyrics = [] 
				this.stop()
				this.musicData = music
				this.isCollect()
				this.$TOOL.data.set('playMusic',music)
				//获取歌词并自动播放
				setTimeout(() => {
				    this.play()
				  //将歌曲添加到当前的播放列表
					this.$TOOL.playListManage.add(this.musicData)
					this.setInitlycTop()
					
				},1000)
			},
			 
			async play(seekTime=0){
				let musicStreamUrl = this.$TOOL.data.get('server_url')+this.$API.play_music.url+'&sid='+this.$TOOL.getSid()+'&id='+this.musicData.id
				// 创建音频对象
				if(!this.audio){
					// this.audio = uni.createInnerAudioContext();
					this.audio = uni.getBackgroundAudioManager();
				}
				// this.audio.title = this.musicData.title;
				// this.audio.singer = this.musicData.singer;
				// this.audio.coverImgUrl = this.musicData.cover;
				if(this.audio.src!==musicStreamUrl){
					this.audio.src = musicStreamUrl;
				}
				
				if (!this.isCreateNotification){
					await this.createNotification();
					
				}
				
				// 

				// 监听音频播放结束事件
				this.audio.onEnded(() => {
					//下一首
					if(this.$refs.bigplayer.cycleMode==='loopone'){
						this.stop() 
						this.$nextTick(()=>{
							this.play()
							this.setInitlycTop()
						})
						 
					}else{
						this.nextPlay()
					}
					
				});
				// 监听音频播放错误事件
				this.audio.onError((err) => {
					//音频播放错误
				});
				 
				
				
				// 开始播放音频
				this.audio.play();
				 
				this.isPlay = true
				this.musicNotification.playOrPause(this.isPlay);
				this.audio.onTimeUpdate(()=>{
					let currentTime = this.audio.currentTime
					this.lyricTime = Math.ceil(currentTime); 
					if(this.lyricTime>this.musicData.music.additional.song_audio.duration){
						this.lyricTime = this.musicData.music.additional.song_audio.duration
					}
					this.getCurrentLyric();
					this.$refs.bigplayer.get_process()

					//通知栏
					let position = Math.max(0, currentTime)
					this.musicNotification.setPosition(position * 1000);
					
				})
				
				
				this.audio.onCanplay(() => {
					this.musicNotification.setPosition(this.audio.currentTime * 1000); 
					this.audio.startTime = seekTime
					let res = this.musicNotification.update({
						//歌曲名字
						songName: this.musicData.title,
						//专辑名字
						artistsName: this.musicData.singer +'-'+this.musicData.album,
						favour: this.collect===1?true:false,
						//专辑图片
						picUrl:this.musicData.cover,
						// 时长
						duration: this.musicData.music.additional.song_audio.duration * 1000
					});
					
					switch (res.code) {
						case -1: //未知错误
							console.log("未知错误");
							return;
						case -2: //没有权限
							this.musicNotification.openPermissionSetting(); //没有权限，跳转设置页面
							return;
					}
				})
				
				
				
				// this.audio.onWaiting(()=>{
				// 	//加载中触发
				// })
				
				//查找歌词
				if(!this.isRequest){
					this.get_lyric()
				}
				
			},
			pause() {
				if (this.audio) {
					this.audio.pause();
					this.isPlay = false;
					this.musicNotification.setPosition(this.audio.currentTime * 1000); 
					this.musicNotification.playOrPause(this.isPlay);
				}
			},
			
			stop(){
				if (this.audio) {
					this.audio.stop();
					this.isPlay = false;
					this.musicNotification.setPosition(this.audio.currentTime * 1000); 
					this.musicNotification.playOrPause(this.isPlay);
				}
			},
			
			seekTo(value){
				let seekTime 
				let duration
				if(this.audio){
					duration = this.audio.duration
					seekTime = duration*(value/100)
					this.audio.seek(seekTime)
					this.play()
				}else{
					let music = this.$TOOL.data.get('playMusic')
					duration = music.music.additional.song_audio.duration
					seekTime = duration*(value/100)
					this.play(seekTime) 
				}
				
			},
			
			seeking(value){
				if(this.audio){
					if(this.audio.paused===false){
						this.pause()
					}
				}
				
				
			},
			
			
			
			nextPlay(){
				//下一首
				
				let cycleMode = this.$refs.bigplayer.cycleMode
				let playList = this.$TOOL.playListManage.list()
				if(playList.length>1){
					let playingId= this.musicData.id
					let playIndex = null
					let nextIndex = null
					playList.forEach((music,index)=>{
						if(music.id===playingId){
							playIndex=index
							return false
						}
					})
					if(cycleMode==='loop' || cycleMode==='loopone'){
						nextIndex = playIndex+1
						if(playIndex==playList.length-1){
							nextIndex = 0
						}
						 
					}else{
						nextIndex = this.$TOOL.getRandomNumbers(0,playList.length-1)
					}
					
					this.playMusic(playList[nextIndex])
				}
			},
			
			prevPlay(){
				//上一首
				 
				let cycleMode = this.$refs.bigplayer.cycleMode
				let playList = this.$TOOL.playListManage.list()
				if(playList.length>1){
					let playingId= this.musicData.id
					let playIndex = null
					let nextIndex = null
					playList.forEach((music,index)=>{
						if(music.id===playingId){
							playIndex=index
							return false
						}
					})
					if(cycleMode==='loop' || cycleMode==='loopone'){
						nextIndex = playIndex-1
						if(playIndex==0){
							nextIndex = playList.length-1
						}
						 
					}else{
						nextIndex = this.$TOOL.getRandomNumbers(0,playList.length-1)
					}
					
					this.playMusic(playList[nextIndex])
				}
				
				
			},
			
			
			get_lyric(){
				let lyrics
				this.$API.get_lyric.request({
					_sid:this.$TOOL.getSid(),
					id:this.musicData.id
				}).then((e)=>{
					 
					if(e.data.lyrics===''){
						this.$API.search_lyric.request({
							_sid:this.$TOOL.getSid(),
							title: this.musicData.title,
							artist: this.musicData.singer,
							limit: 1
						}).then((e2)=>{
							if(e2.data){
								lyrics = e2.data.lyrics[0].additional.full_lyrics
								this.formatLyric(lyrics) 
							}
							
						})
					}else{
						lyrics = e.data.lyrics
						this.formatLyric(lyrics) 
					}
				})
			},
			formatLyric(lyrics){
				
				this.lyrics= this.$TOOL.formatLyric(lyrics)
				//将当前歌词储存
				this.$TOOL.data.set('lyrics',this.lyrics)
				this.isRequest = true
			},
			
			//获取当前歌词 
			getCurrentLyric(){
				let j;
				for(j=0; j<this.lyrics.length-1; j++){
					if(this.lyricTime == this.lyrics[j].time){
						if(this.lyrics[j].text){
							this.palylrc = this.lyrics[j].text
							return false
						}
					} 
				}
				 
			},
			
			toPlayer(){
				this.showBigPlayer = true
			},
			
			showPlaylist(){
				this.$refs.playList.show()
			},
			
			isCollect(){
				if(this.musicData){
					let id = this.musicData.id
					let isCollect = this.$TOOL.collectListManage.isCollect(id)
					this.collect = isCollect
					this.musicNotification.favour( this.collect===1?true:false );
				}
			},
			
			
			checkOverlayDisplayPermission() {
				// 检查是否有浮窗权限
				return this.musicNotification.checkOverlayDisplayPermission()
			},
			//创建通知栏
			createNotification() {
				// 创建通知栏，要创建通知栏成功才能做别的操作
				return new Promise((resolve, reject) => {
					this.musicNotification.createNotification(() => {
						this.isCreateNotification = true;
						resolve();
					})
					this.lockActivity()
				})
			},
			
			lockActivity() {
				// 设置锁屏页，同时返回授权状态
				if(this.checkOverlayDisplayPermission()) {
					// 有权限
					this.musicNotification.openLockActivity(true) 
				} else {
					// 没有权限，弹出一个对话框
					this.showLockActivityModal(() => this.lockActivity())
				}
			},
			showLockActivityModal(callback) {
				uni.showModal({
					content: '该功能需要开启悬浮窗权限',
					success: ({ confirm }) => {
						if (confirm) {
							// 用户点击确定，注册授权监听
							plus.globalEvent.addEventListener('openLockActivity', ({
								type
							}) => {
								// 获得悬浮窗权限
								if (type) callback();
								// 注销授权监听
								plus.globalEvent.removeEventListener('openLockActivity');
							});
							/**
							 * 没有悬浮窗权限，跳转设置页面
							 */
							this.musicNotification.openOverlaySetting();
						}
					}
				});
			},
			
			
			//通知栏初始化
			initNotification(){
				this.musicNotification.init({
					path:'', //点击要跳转的页面
				}) 
				// 监听生命周期事件回调
				plus.globalEvent.addEventListener('musicLifecycle', (e) => {
					console.log("生命周期", e);
				});
				// 监听暂停或播放按钮事件回调
				plus.globalEvent.addEventListener('musicNotificationPause', (e) => {
					let isPlaying = this.isPlay
					this.musicNotification.playOrPause(!isPlaying);
					this.musicNotification.setPosition(this.audio.currentTime * 1000); 
					if (isPlaying) {
					    
						this.pause();
					} else {
					    this.audio.play();
					    this.isPlay = true
					}  
				});
				// 监听播放上一首按钮事件回调
				plus.globalEvent.addEventListener('musicNotificationPrevious', (e) => {
					this.prevPlay()
					 
				});
				// 监听播放下一首按钮事件回调
				plus.globalEvent.addEventListener('musicNotificationNext', (e) => {
					this.nextPlay()
					 
				});
				
				// 监听收藏按钮事件回调
				plus.globalEvent.addEventListener('musicNotificationFavourite', (e) => {
					this.$refs.bigplayer.collect()
					this.musicNotification.favour( this.collect===1?true:false );
				});
				
				 
				 
				// 监听耳机事件回调，注意只能在应用播放音乐的时候才能接收到事件
				plus.globalEvent.addEventListener('musicMediaButton', (e) => {
					// console.log("耳机按钮事件回调", e);
					// uni.showToast({
					// 	title: JSON.stringify(e),
					// 	icon:'none',
					// 	position:"center"
					// })
					switch (e.type) {
						case 'headset':
							// 有线耳机事件 拔出： 0, 插入：1
							if (e.keyCode === 0) {
								this.pause();
							}
							break;
						case 'bluetooth':
							// 蓝牙耳机事件 断开： 0, 打开：1，连接：2
							if (e.keyCode === 0) {
								this.pause();
							}
							break;
						case 'mediaButton':
							// 耳机按键事件，如果有的耳机按键按了没反应，不要怀疑是插件问题，插件已经把事件直接返回了，没有事件，那就是耳机根本没发起事件
							switch (e.keyCode) {
								case 79:
									this.pause();
									break;
								case 87:
									this.nextPlay();
									break;
								case 88:
									this.prevPlay();
									break;
								case 126:
									this.play();
									break;
								case 127:
									this.pause();
									break;
							}
							break;
					}
				});
				
				// 监听通知栏进度条拖动事件回调
				plus.globalEvent.addEventListener('musicSeekTo', (e) => {
					this.audio.seek(e.position)
					 
				})
				 
				
			},
			
		}
	}
</script>

<style lang="scss" scoped>
	 
	
	.bigPlayer{
		width: 100%;
		height: 100vh;
		position: absolute;
		left: 0;
		top: 0;
		z-index: 9999;
		transition: 0.3s;
		background: #ffffff;
	}
	 
	.playerBox{
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 20rpx 40rpx;
		position: fixed;
		bottom: 0rpx;
		background: #ffffff;
		width: calc(100vw - 80rpx);
		box-shadow: 0 0 12px #0000001f; 
		overflow: hidden;
		z-index: 999; 
		>view{
			
			&:first-child{
				display: flex;
				align-items: center;
				justify-content:flex-start;
				width: calc(100% - 140rpx);
				image{
					width: 90rpx;
					height: 90rpx;
					min-width: 90rpx;
					border-radius: 12rpx;
				}
				>view{
					margin-left: 24rpx;
					font-size: 28rpx;
					width: calc(100% - 112rpx);
					>view{
						width: 100%; 
						&:first-child{
							white-space: nowrap;
							overflow: hidden;
							text-overflow:ellipsis;
						}
						&:last-child{
							font-size: 20rpx;
							height: 34rpx;
							font-weight: 400;
							opacity: 0.7;
							margin-top: 6rpx;
							white-space: nowrap;
							overflow: hidden;
							text-overflow:ellipsis;
						}
					}
				} 
			}
			
			&:nth-child(2){
				display: flex;
				align-items: center;
				justify-content:flex-start;
				>view{
					&:last-child{
						margin-left: 40rpx;
					}
				}
				 
			}
			 
		}
	}
</style>